C SS LA YOUT WITH FLEXBOX

Lay​ing out a de​sign with CSS is fraught with peril of cross-browser bugs and mys​te​ri​ously col​-
laps​ing mar​gins. But new tools like flexbox have trans​formed this once odi​ous task into some​-
thing you shouldn't dread. By the end of this chap​ter you'll be cod​ing up new lay​outs for your
de​sign faster than you can think of them.

R

e​mem​ber those old car​toons with the road run​ner and the coy​ote?

Rocket  pro​pelled  roller​skates,  bot​tled  light​ning,  bun​dles  of  dy​na​-

mite, mag​netic bird  seed, razor boomerangs, "super"  bombs and giant

tram​po​lines -- no tech​nol​ogy could catch the bird. Every tool back​fired

and sent Wile E. Coy​ote plum​met​ing to hillar​i​ous death.

Using CSS to lay​out your de​sign is like try​ing to catch the road run​ner

with a jet-pow​ered pogo stick. It won't end well.

CSS sucks at lay​out

Noth​ing is more frus​trat​ing than writ​ing a pile of code, re​fresh​ing your

browser  and  see​ing  a  jum​bled  mess  of  over​lap​ping  text  and  im​ages.

You  can't  use  ta​bles  be​cause  they  aren't  se​man​tic.  Floats  and  clears

never  do  what  you  ex​pect.  Just  to  cen​ter  some​thing  on  the  page  re​-

quires strange  in​can​ta​tions of  auto mar​gins or  text-align --  the cen​ter

tag is right out.

But  you  know  what?  This  is  old  news  be​cause  CSS  doesn't  suck  at

lay​out any​more.

In​tro​duc​ing Flexbox

Once you spend some time with flexbox you'll feel like an un​stop​pable

super hero of CSS. Your footer will stay at the bot​tom of the page where

it be​longs. Your list items will flow ef​fort​lessly into neat lit​tle columns.

Divs will shrink and grow and fly in del​i​cate for​ma​tions like the Blue An​-

gels.  Image  tags  will  dance  and  jump  and  sing  songs  of  your  de​sign

prowess.

"Wait, let's not get car​ried away" you say, "Flexbox is too new. You

can't even use it in IE9."

It  doesn't  mat​ter.  Think  about  it:  how  many  browsers  does  a  PSD

work in? None? Ex​actly. As a de​signer you're not build​ing the final ver​-

sion of the de​sign. You don't care if flexbox doesn't work in Opera Mini

be​cause the comp you are cre​at​ing for your client only needs to run in

Chrome. Worry about Sea​Mon​key later.

The key  is to keep your  lay​out code sep​a​rate from  your style code.

Cre​ate an en​tirely new stylesheet just for lay​out. Du​pli​cate se​lec​tors if

you have to. By keep​ing it sep​a​rate, it's eas​ier for a front-end de​vel​oper

to  cre​ate  the final,  pro​duc​tion-ready  lay​out  code  once the  de​sign  has

so​lid​i​fied enough.

Div​ing into Flexbox

You only need to know a hand​ful of CSS prop​er​ties and a lit​tle ter​mi​nol​-

ogy to use flexbox.

Every​thing starts with the flex con​tainer. Once an el​e​ment is set as a

flex con​tainer it's chil​dren fol​low the flexbox rules for lay​out in​stead of

the stan​dard block, in​line and in​line-block rules. Within a flex con​tainer

items line up  on the "main axis"  and the main axis can  ei​ther be hor​i​-

zon​tal  or  ver​ti​cal so  you  can  arrange items  into  columns  or rows.  The

axes are in​vis​i​ble, but in the ex​am​ples added, vis​i​ble lines will help you

see how the main axis and cross axis are ori​ented.

Every ex​am​ple uses the same HTML.

<div class="flex">

  <header>
  </header>

  <article>
  </article>

  <aside>
  </aside>

  <footer>
  </footer>

</div>

There is a lit​tle CSS to style the boxes and give them some di​men​sion,

plus the div is set as a flex con​tainer.

.flex{
    display: flex;
}

.flex > *{
    min-width: 100px;
    min-height: 100px;
}

header{
    background: rgba(200, 200, 200, 1);
}
article{
    background: rgba(200, 200, 200, .8);
}
aside{
   background: rgba(200, 200, 200, .6);
}
footer{
   background: rgba(200, 200, 200, .4);
}

      
  
  
  
  
A quick overview of flexbox ter​mi​nol​ogy

The  first  ex​am​ple  cen​ters  the  flex  con​tainer  chil​dren,  (the  <header>,

<ar​ti​cle>,  <aside>  and  <footer>),  ver​ti​cally  and  hor​i​zon​tally.  Ver​ti​cal

cen​ter​ing  with CSS  used to  be re​ally  hard, with  flexbox it's  one line  of

CSS.

flex-flow: row;
align-items: center; /* This centers the items vertically. */
justify-content: center; /* This centers everything horizontally.…

The flex-flow prop​erty de​ter​mines which way the main axis is ori​ented,

(the cross-axis is al​ways per​pindic​u​lar to the main axis). When it's set

to row, the main axis is hor​i​zon​tal, and it's ver​ti​cal when set to col​umn.

You  use  jus​tify-con​tent  to  de​ter​mine  where  the  items  line  up  on  the

main axis and align-items to shift them around on the cross-axis.

The main axis is hor​i​zon​tal, so the the flex items are lined up in a row.

What  hap​pens  if  the  main  axis  is  ver​ti​cal,  (so  flex-flow  is  set  to  col​-

umn)?

The main axis is ver​ti​cal, so the the flex items are lined up in a col​umn.

In the ex​am​ples you've seen so far, jus​tify-con​tent and align-items have

been set to cen​ter but you can also move them to the be​gin​ning or end

of ei​ther axis. To  move the flex con​tainer chil​dren to  the end of ei​ther

axis, set jus​tify-con​tent or align-items to flex-end. To move them to the

be​gin​ning use flex-start.

The con​tent is in the bot​tom right cor​ner be​cause it's aligned with the end of the main axis and the end of the cross axis.

Space around flex items

In​stead  of  push​ing  items  to  the  be​gin​ning,  cen​ter  or  end  of  the  main

axis, you can dis​trib​ute space evenly around the items. Set jus​tify-con​-

tent to space-around or space-be​tween.

The flex items are cen​tered on the cross axis and have space evenly dis​trib​uted around them along the main axis.

Shrink​ing and grow​ing

You can de​fine the size of flex items. This lets you cre​ate lay​outs with,

for  ex​am​ple, a  col​umn with  a  fixed width  and  a col​umn  that grows  or

shrinks with the space avail​able.

You achieve this  magic by set​ting three sep​a​rate  prop​er​ties on the

chil​dren of the  flex con​tainer: flex-grow, flex-shrink,  and flex-ba​sis.  Or

you can com​bine all three val​ues in one prop​erty: flex.

The left flex item stretches to fill about a third of the screen and the oth​ers shrink to fill the rest evenly. In this case I've
also de​cided to have them grow and fill the ver​ti​cal space.

The skinny col​umn is fixed at 50 pix​els. The other columns grow and shrink to fill in the re​main​ing space evenly.

Be​yond sta​tic im​ages and text

You haven't seen much code up to this point be​cause the CSS prop​erty

names  don't  map  well  to  the  very  sim​ple  con​cepts  be​hind  flexbox.

Flexbox  makes  much  more  sense  when  you  can  watch  and  see  what

hap​pens on the screen as the code is up​dated. Here are three screen​-

casts to help you add flexbox to your ar​se​nal. You can also lean on this

cheat sheet while you get used to the ter​mi​nol​ogy.

The ba​sics

Grow​ing and shrink​ing flex items

More ad​vanced odds and ends

Ex​am​ples from Real Web​sites

Flexbox  doesn't  solve  every  lay​out  prob​lem  but  it  cer​tainly  fixes  the

worst of them. As you look at a few real world ex​am​ples you will learn a

few  other  tech​niques  for  ar​rang​ing  el​e​ments  on  the  page  but  flexbox

alone will get you 90% of the way most of the time.

37sig​nals

The prod​uct sec​tion of the 37sig​nals home​page.

You're  look​ing  at  three  divs cen​tered  hor​i​zon​tally  —  cer​tainly  not  the

most  com​pli​cated  lay​out  of  all  time.  Even  so,  be​fore  flexbox  cre​at​ing

this  kind  of  lay​out  re​quired  some  thought;  cen​ter​ing  el​e​ments  on  the

page was not in​tu​itive.

The HTML

  <div class="products">
    <div>
      <img src="basecamp.png"></img>
      <h2><a href="">Basecamp</a></h2>
      <h3>Manage Projects</h3>
      <p>Used by millions for product management.</p>
    </div>
    <div>
      <img src="highrise.png"></img>
      <h2><a href="">Highrise</a></h2>
      <h3><a href="">Manage Contacts</a></h3>
      <p>Know the people you do business with.</p>
    </div>
    <div>
      <img src="campfire.png"></img>
      <h2><a href="">Campfire</a></h2>
      <h3>Work in Real-Time</h3>
      <p>Group chat rooms for your business.</p>
    </div>
  </div>  

  
No lay​out yet

Be​fore any lay​out logic it's all mushed to the left and in a col​umn.

This  is  how  the  markup  ren​ders  with  just  enough  CSS  to  make  the

styling look about the same. You are look​ing at the de​fault browser lay​-

out be​fore we've ap​plied any flexbox rules. The three boxes are div el​e​-

ments. Div el​e​ments are block el​e​ments and block el​e​ments stack, they

don't flow next to each other.

First let's cen​ter it on the page and get every​thing flow​ing into a row.

The CSS

  .products{
  display: flex;
  flex-flow: row;
  justify-content: center;
  }

Five lines of CSS later...

Five lines of flexbox code set​ting three prop​er​ties and our Base​camp ex​am​ple is start​ing to look pretty good.

The div wrap​ping the prod​uct divs was set to "dis​play: flex" to make it a

flex con​tainer. Then to get its items into a row, set the flex-flow prop​-

erty to "row".

Get​ting every​thing cen​tered was easy. Jus​tify-con​tent let's you move

flex items on the main axis. In this case the main axis is hor​i​zon​tal be​-

cause the flex-flow prop​erty is set to "row". When the main axis is hor​i​-

zon​tal,  jus​tify-con​tent  will  move  the  items  to  the  left  and  right.  If  the

main  axis  is  ver​ti​cal,  (set  flex-flow  to  col​umn),  jus​tify-con​tent  moves

the items up and down in​stead of left and right. To cen​ter the prod​uct

divs in the ex​am​ple hor​i​zon​tally,set jus​tify-con​tent to "cen​ter".

  
The  first  real  world  ex​am​ple is  al​most  done.  The  mid​dle  con​tainer

needs  some  space  around  it  and  all  of  the  items  in  each  con​tainer

should be cen​tered hor​i​zon​tally.

To  cen​ter  the  items  in  the  div  it's  eas​i​est  to  think  about  them  as

flow​ing in a col​umn and then cen​ter​ing them on the cross axis. So in this

case the main axis is ver​ti​cal and the cross axis is hor​i​zon​tal. Here's the

code:

  /*
  1. Make all of the product divs flex containers.
  2. Set their items to flow into a column.
  3. Center them left-to-right by centering them
  on the cross axis using align-items.
  */
  .products > div{
  display: flex;
  flex-flow: column;
  align-items: center;
  }

  /* Using selectors like this
  is covered in another chapter.*/
  .products > div:nth-child(2){
  margin: 0 2em;
  }

The fin​ished ex​am​ple with every​thing lined up in​side the prod​uct divs and mar​gin around the mid​dle.

  
  
Anatomy of a Tweet

An ex​am​ple tweet.

The HTML

  <div class="tweet">
    <div class="content">
      <img src="aaron.png"></img>
      <h2>Aaron Gustafson <span>@AaronGustafson</span></h2>
      <time>12h</time>
      <p>

Smartphone Browser localStorage is up to 5x Faster than N…
<a href="/">mobify.com/blog/smartphon ...</a>

      </p>
      <ul class="actions">

<li><a href="">Collapse</a></li>
<li><a href="">Reply</a></li>
<li><a href="">Retweet</a></li>
<li><a href="">Favorite</a></li>
<li><a href="">More</a></li>

      </ul>
      <ul class="meta">

<li class="retweets">

          <span>7</span>
          <span>RETWEETS</span>

</li>
<li class="favorites">

          <span>5</span>
          <span>FAVORITES</span>

</li>
<li class="people">

          <ul class="people">
            <li>
              <img src="people1.jpg"/>
            </li>
            <li>
              <img src="people2.jpg"/>

 
 
 
 
 
 
 
 
 
 
 
 
            </li>
            <li>
              <img src="people3.jpg"/>
            </li>
            <li>
              <img src="people4.jpg"/>
            </li>
            <li>
              <img src="people5.jpg"/>
            </li>
            <li>
              <img src="people6.jpg"/>
            </li>
            <li>
              <img src="people7.jpg"/>
            </li>
          </ul>
        </li>
      </ul>
      <time>4:35 AM - 24 May 13</time>
    </div>
    <div class="reply">
      <div contenteditable="true">

Reply to <span>@AaronGustafson</span>

      </div>
    </div>
  </div>

 
  
No lay​out

The de​fault browser lay​out: stacked in a col​umn and pushed over to the left.

Per​fect is the enemy of done

When con​fronted with a con​found​ing lay​out prob​lem a com​mon pit​fall

is to waste time find​ing the "best" so​lu​tion. As soon as you find your​self

pon​der​ing the mer​its of chang​ing the markup and wor​ry​ing about mess​-

ing up the se​man​tics, stop what you're doing and see if ab​solute po​si​-

tion​ing would work.

When​ever you're think​ing about tech​ni​cal de​ci​sions you're not think​-

ing about de​sign. Re​mem​ber, your job is to cre​ate a comp, not the final

site. The code  you are writ​ing will be re​worked  and rewrit​ten so don't

spend any time mak​ing it per​fect -- per​fect is the enemy of done.

The first chal​lenge with the tweet is the user pro​file image and the

date  tag.  Al​though  not  ob​vi​ous  in  this  ex​am​ple  the  tweet  text  flows

under  the  date  and  the  pro​file  image seems  to  have  it's  own  col​umn.

The way the markup was writ​ten does not make a flexbox lay​out im​me​-

di​ately ob​vi​ous. You might be tempted to spend a few min​utes to fig​ure

out  a  way  you  could  change  the markup  and  get  the  lay​out  you  want

with flexbox, but here is an ex​am​ple where you could eas​ily get mired

down  in  tech​ni​cal  de​tails.  In​stead,  just  ab​solutely  po​si​tion  both  el​e​-

ments where you want them. There is dan​ger in ab​solute po​si​tion​ing for

pro​duc​tion code, but it's fine in small doses for pro​to​typ​ing.

The CSS

  /* create the space on the left for the profile image*/
  .tweet .content,
  .tweet .reply{
  padding-left: 70px;
  }

  /*move the image to the left into the column*/
  .content > img{
  position: absolute;
  margin-left: -60px;
  }

  /*
  Move the timestamp up and to the right
  Used "em" instead of pixels here, but pixels
  are just fine.
  */
  .content > time:first-of-type{
  position: absolute;
  margin-top: -1.5em;
  margin-left: 30em;
  }

  /*Added some vertical padding to all
  of the elements in the content div.
  */
  .content > *{
  padding: .25em 0;
  }

  
  
  
  
Ab​solutely po​si​tioned two el​e​ments

What the tweet looks like after ab​solutely po​si​tion​ing two el​e​ments and adding some spac​ing.

The next step is to take the ac​tions, (e.g. col​lapse, reply, retweet, etc.),

the retweets and fa​vorites and the list of small pro​file pic​tures and put

them into rows in​stead of columns.

A dash of flexbox

    .actions, li.people, .meta, .people > ul {
    display: flex;
    }

Al​most done

One line of CSS and it's al​most done.

El​e​ments  in  con​tain​ers  are  arranged  into  rows  by  de​fault  so  you  just

need to set the con​tainer to dis​play: flex.

You'll no​tice in the real tweet the num​bers are on top of "fa​vorites"

and "retweets". There are two ways to do this. The first is to treat them

like flex  con​tain​ers and put  them into a col​umn.  The sec​ond way  is to

make each of the spans wrap​ping the num​bers into a block el​e​ment in​-

stead of in​line.

The  sec​ond  way  is  only  ob​vi​ous  if  you  know  that  block  el​e​ments

stack. The beauty of flexbox is you don't need to know the ins and outs

of  block,  in​line  or  in​line-block  el​e​ments.  Learn  the  ba​sics  but  don't

waste time — use flexbox when it's not ob​vi​ous.

    
  .meta .retweets,
  .meta .favorites{
  display: flex;
  flex-flow: column;
  }

Stack the el​e​ments

Fin​ished

Two more lines of CSS for lay​out plus some spac​ing and bor​ders around key el​e​ments. Yes, it's miss​ing icons for the ac​-
tion links. It's just an ex​am​ple.

  
CSS-Tricks

In​cluded in the book ex​am​ple code is a third, much more com​pli​cated

ex​am​ple  for  you  to  look  at.  Most  of  the  CSS-Tricks  forum  has  been

recre​ated using flexbox for lay​out.

The CSS-Tricks forum re​verse en​gi​neered using flexbox.

Load the ex​am​ple in Chrome and use the skills you learned in the chap​-

ter on using Chrome's De​vel​oper tools to see how some of the el​e​ments

in the ex​am​ple are laid out using flexbox.

Tips and tricks

When  ab​solutely  po​si​tion​ing  an  el​e​ment  use  mar​gins  in​stead  of  top,

left,  right,  bot​tom.  El​e​ments  ab​solutely  po​si​tioned  with  mar​gins  are

more con​sis​tent across dif​fer​ent screen res​o​lu​tions.

Use ems in​stead of pix​els. Ems ad​just when you change font-size. If you

in​creased the base font size in this ex​am​ple the date would main​tain its

po​si​tion.

Use padding in​stead of mar​gin for spac​ing. Spaces cre​ated with mar​gin

some​times col​lapse into each other in​stead of stack​ing. Some​times you

want this but most of the time it's not help​ful. Padding doesn't col​lapse

so it's more pre​dictable than using mar​gins.

Use the uni​ver​sal se​lec​tor, *, with​out fear. Ex​pe​ri​enced web de​vel​op​ers

avoid  the  uni​ver​sal  se​lec​tor  for  per​for​mance  rea​sons.  You  shouldn't

spend  any time  think​ing  about  this. There  are  per​for​mance is​sues  but

noth​ing to worry about when cre​at​ing the ini​tial de​sign.

The key to cre​at​ing more com​pli​cated lay​outs with flexbox is to break it

into pieces. Don't be afraid to make every​thing a flex con​tainer if that's

what works for you.

Sum​mary

Mas​ter​ing  the  art  of  lay​ing  out  el​e​ments  on  a  page  using  CSS  is  the

hard​est part of de​sign​ing in the browser.

Flexbox has made this task much eas​ier.

Here is your flexbox cheat sheet, use it wisely.

Every ex​am​ple in this chap​ter has code, in​cluded with the book, you can

look at and use in your pro​jects. Open the ex​am​ples, (in​cluded with this

book), with Chrome and use the de​vel​oper tools to get a closer look.

The real-world ex​am​ples are also in​cluded with your copy of the book

and  hosted  on  the  web.  The  37sig​nals  ex​am​ple,  the  twit​ter  ex​am​ple

and the CSS-Tricks forum.

